package com.pw.lit.controller;

import com.pw.lit.bean.*;
import com.pw.lit.bean.Collection;
import com.pw.lit.service.*;
import com.pw.lit.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/User")
public class UserController {
    //管理员
    @Autowired
    private AdminService adminService;
    //用户接口
    @Autowired
    private UserServiceImpl userService;
    //uid登录接口
    @Autowired
    private UidloginService uidloginService;
    //email登录接口
    @Autowired
    private EmailloginService emailloginService;
    //关注接口
    @Autowired
    private FollowService followService;
    //博客接口
    @Autowired
    private BlogService blogService;
    //评论接口
    @Autowired
    private CommentService commentService;
    //回复接口
    @Autowired
    private ReplyService replyService;
    //收藏接口
    @Autowired
    private CollectionService collectionService;
    //浏览历史
    @Autowired
    private HistoryService historyService;
    //登录日志
    @Autowired
    private IplogService iplogService;
    //消息
    @Autowired
    private MessageService messageService;
    //发邮件
    @Autowired
    private JavaMailSender javaMailSender;

    //跳转登录页面
    @RequestMapping("/login")
    public String login(Model model, HttpSession session) {
        model.addAttribute("em", "1");
        session.removeAttribute("msg");
        return "FrontPages/login/login";
    }

    //uid登录
    @RequestMapping("/loginbyuid")
    public String loginByUid(Model model, @RequestParam("uid") String uid, @RequestParam("password") String password, HttpSession session) {
        Uidlogin uidlogin;
//        if (uid.equals("admin") && password.equals("admin")) {
//            model.addAttribute("msg", "登录成功!");
//            return "ServicePages/aindex";
//        }
        if (uid.equals("admin")) {
            Admin admin = adminService.selectByPrimaryKey(1);
            if (admin.getPassword().equals(password)) {
                model.addAttribute("msg", "登录成功!");
                return "ServicePages/aindex";
            }
        }
        model.addAttribute("em", "1");
        if (uidloginService.selectByPrimaryKey(uid) != null) {
            uidlogin = uidloginService.selectByPrimaryKey(uid);
            if (uidlogin.getPassword().equals(md5(password))) {
                session.setAttribute("msg", "登录成功!");
                User user = userService.selectByPrimaryKey(uidlogin.getId());
                saveip(user);
                session.setAttribute("user", user);
                session.setAttribute("logstatus", "1");
                return "FrontPages/login/login";
            } else {
                session.setAttribute("msg", "密码错误，请重新输入！");
                session.setAttribute("logstatus", "0");
                return "FrontPages/login/login";
            }
        } else {
            session.setAttribute("msg", "账号错误，请重新输入！");
            session.setAttribute("logstatus", "0");
            return "FrontPages/login/login";
        }
    }

    //发送邮件
    @RequestMapping("/sendemail")
    @ResponseBody
    public int sendemail(HttpSession session, @RequestParam("email") String email) {
        System.out.println("发送验证码");
        String ver = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1980613755@qq.com");
        message.setTo(email);
        message.setSubject("来自爱IT的验证码");
        message.setText("你的验证码是：" + ver);
        javaMailSender.send(message);
//        String ver = "1234";
        session.setAttribute("verfication", ver);
        return 1;
    }

    //邮箱登录
    @RequestMapping("/loginbyemail")
    public String loginByEmail(Model model, @RequestParam("email") String email, @RequestParam("verification") String verification, HttpSession session) {
        Emaillogin emaillogin;
        model.addAttribute("em", "2");
        if (emailloginService.selectByPrimaryKey(email) != null) {
            emaillogin = emailloginService.selectByPrimaryKey(email);
            String Email = "";
            if (session.getAttribute("verfication") != null) {
                Email = session.getAttribute("verfication").toString();
            }
            if (Email.equals(verification)) {
                session.setAttribute("msg", "登录成功!");
                User user = userService.selectByPrimaryKey(emaillogin.getId());
                saveip(user);
                session.setAttribute("user", user);
                session.setAttribute("logstatus", "1");
                session.removeAttribute("verfication");
                return "FrontPages/login/login";
            } else {
                session.setAttribute("msg", "验证码错误！请重新输入");
                session.setAttribute("logstatus", "0");
                return "FrontPages/login/login";
            }
        } else {
            session.setAttribute("msg", "邮箱错误！请重新输入");
            session.setAttribute("logstatus", "0");
            return "FrontPages/login/login";
        }
    }

    //存IP
    public void saveip(User user) {
        try {
            InetAddress ip = Inet4Address.getLocalHost();
            Iplog iplog = new Iplog();
            iplog.setId(user.getId());
            iplog.setIp(ip.getHostAddress());
            iplogService.insert(iplog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //注册页面
    @RequestMapping("/register")
    public String register(HttpSession session) {
        session.removeAttribute("msg");
        return "FrontPages/login/register";
    }

    //注册
    @RequestMapping("/reg")
    public String reg(@RequestParam("uid") String uid,
                      @RequestParam("password") String password,
                      @RequestParam("email") String email,
                      @RequestParam("verification") String verification,
                      HttpSession session,
                      User user) {
        System.out.println("注册");
        if (uidloginService.selectByPrimaryKey(uid) != null) {
            session.setAttribute("msg", "该昵称已经存在！");
        } else if (emailloginService.selectByPrimaryKey(email) != null) {
            session.setAttribute("msg", "该邮箱已经存在！");
        } else if (session.getAttribute("verfication") == null) {
            session.setAttribute("msg", "还没有发送验证码！");
        } else if (session.getAttribute("verfication").equals(verification)) {
//            User user=new User();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = sdf.format(date);
            user.setUid(uid);
            user.setPassword(md5(password));
            user.setEmail(email);
            user.setSex("1");
            user.setDate(time);
            user.setFollows(0);
            user.setFans(0);
            user.setBlogNumber(0);
            user.setZanNumber(0);
            user.setImg("/layui/images/head-pic/head5.jpg");
            try {
                userService.insert(user);
                addUillogin(user);
                addEmaillogin(user);
                checkreg(user, session);
                session.setAttribute("msg", "注册成功！");
                session.setAttribute("logstatus", "1");
                session.setAttribute("user", user);
                session.removeAttribute("verfication");
                return "FrontPages/login/register";
            } catch (NullPointerException e) {
                session.setAttribute("logstatus", "0");
                session.setAttribute("msg", "注册失败！");
                return "FrontPages/login/register";
            }
        }
        session.removeAttribute("verfication");
        session.setAttribute("logstatus", "0");
        return "FrontPages/login/register";
    }

    //md5加密
    public String md5(String str) {
        String newstr = null;
        try {
            //确定计算方法
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            //加密后的字符串
            newstr = new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return newstr;
    }

    //注册成功添加邮箱登录
    private void addEmaillogin(User user) {
        Emaillogin emaillogin = new Emaillogin();
        User user1 = userSelectByUid(user.getUid());
        if (emailloginService.selectByPrimaryKey(user.getEmail()) == null) {
            emaillogin.setEmail(user1.getEmail());
            emaillogin.setId(user1.getId());
            emaillogin.setPassword(user1.getPassword());
            emailloginService.insert(emaillogin);
        }
    }

    //注册成功添加uid登录
    public void addUillogin(User user) {
        Uidlogin uidlogin = new Uidlogin();
        User user1 = userSelectByUid(user.getUid());
        if (uidloginService.selectByPrimaryKey(user.getUid()) == null) {
            uidlogin.setUid(user1.getUid());
            uidlogin.setId(user1.getId());
            uidlogin.setPassword(user1.getPassword());
            uidloginService.insert(uidlogin);
        }
    }

    //通过uid获取user
    private User userSelectByUid(String uid) {
        UserExample userExample = new UserExample();
        UserExample.Criteria usercriteria = userExample.createCriteria();
        usercriteria.andUidEqualTo(uid);
        List<User> list = userService.selectByExample(userExample);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    //检查是否注册成功
    public String checkreg(User user, HttpSession session) {
        if (uidloginService.selectByPrimaryKey(user.getUid()) != null &&
                emailloginService.selectByPrimaryKey(user.getEmail()) != null) {
            session.setAttribute("msg", "注册成功！");
            session.setAttribute("logstatus", "1");
            return "FrontPages/login/register";
        } else {
            UserExample userExample = new UserExample();
            UserExample.Criteria usercriteria = userExample.createCriteria();
            usercriteria.andUidEqualTo(user.getUid());

            UidloginExample uidloginExample = new UidloginExample();
            UidloginExample.Criteria uidcriteria = uidloginExample.createCriteria();
            uidcriteria.andUidEqualTo(user.getUid());

            userService.deleteByExample(userExample);
            uidloginService.deleteByExample(uidloginExample);
            session.setAttribute("msg", "注册失败！");
            session.setAttribute("logstatus", "0");
            return "FrontPages/login/register";
        }
    }

    public User selectByUid(String uid) {
        if (uidloginService.selectByPrimaryKey(uid) != null) {
            Uidlogin uidlogin = uidloginService.selectByPrimaryKey(uid);
            return userService.selectByPrimaryKey(uidlogin.getId());
        } else return null;
    }

    public User selectByEmail(String email) {
        UserExample userExample = new UserExample();
        UserExample.Criteria usercriteria = userExample.createCriteria();
        usercriteria.andEmailEqualTo(email);
        List<User> list = userService.selectByExample(userExample);
        if (!list.isEmpty()) {
            return list.get(0);
        } else
            return null;
    }

    //找回密码页面
    @RequestMapping("/retrieve")
    public String retrieve(HttpSession session) {
        session.removeAttribute("msg");
        return "FrontPages/login/retrieve";
    }

    //找回密码
    @RequestMapping("/ret")
    public String ret(@RequestParam("email") String email,
                      @RequestParam("verification") String verification,
                      @RequestParam("password") String password,
                      @RequestParam("repassword") String repassword,
                      HttpSession session) {
        System.out.println("重置密码");
        if (selectByEmail(email) != null) {
            User user = selectByEmail(email);
            if (session.getAttribute("verfication") != null) {
                if (session.getAttribute("verfication").equals(verification)) {
                    if (user.getPassword().equals(md5(password))) {
                        session.setAttribute("msg", "旧密码不能与新密码相同!");
                    } else if (!password.equals(repassword)) {
                        session.setAttribute("msg", "两次输入的密码不相同!");
                    } else {
                        user.setPassword(md5(password));
                        userService.updateByPrimaryKey(user);
//                        Uidlogin uidlogin = uidloginService.selectByPrimaryKey(user.getUid());
//                        uidlogin.setPassword(password);
//                        uidloginService.updateByPrimaryKey(uidlogin);
//                        Emaillogin emaillogin = emailloginService.selectByPrimaryKey(user.getEmail());
//                        emaillogin.setPassword(password);
//                        emailloginService.updateByPrimaryKey(emaillogin);
                        session.setAttribute("msg", "重置密码成功!");
                    }
                } else
                    session.setAttribute("msg", "验证码输入错误!");
            } else
                session.setAttribute("msg", "还没有发送验证码!");
        } else
            session.setAttribute("msg", "邮箱输入错误!");
        return "FrontPages/login/retrieve";
    }

    //个人中心
    @RequestMapping("/userfile/{uid}")
    public String userfile(Model model,
                           @PathVariable("uid") String uid) {
        setfollw(model, uid);
        sethis(model, uid);
        model.addAttribute("user1", selectByUid(uid));
        return "FrontPages/login/userfile";
    }

    //获取粉丝和关注
    public Model setfollw(Model model, String uid) {
        List<Follow> follows;
        List<User> fans;
        try {
            follows = selectfollows(uid);
        } catch (Exception e) {
            follows = null;
        }
        try {
            fans = selectfans(uid);
        } catch (Exception e) {
            fans = null;
        }
        if (follows != null) {
            model.addAttribute("follows", follows);
        }
        if (fans != null) {
            model.addAttribute("fans", fans);
        }
        return model;
    }

    //获取历史记录
    public Model sethis(Model model, String uid) {
        User u = selectByUid(uid);
        HistoryExample example = new HistoryExample();
        HistoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        List<History> histories = null;
        List<Blog> blogList = new ArrayList<>();
        try {
            histories = historyService.selectByExample(example);
            for (History h : histories) {
                blogList.add(blogService.selectByPrimaryKey(h.getBid()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("没有历史记录!");
        }
        if (histories != null) {
            histories.sort(Comparator.comparing(History::getHid).reversed());
            model.addAttribute("historys", histories);
        }
        if (blogList != null) {
            blogList.sort(Comparator.comparing(Blog::getBid).reversed());
            model.addAttribute("bloghis", blogList);
        }
        return model;
    }

    //获取收藏列表
    @RequestMapping("/getcollection")
    @ResponseBody
    private Map<String, Object> getcollection(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        CollectionExample example = new CollectionExample();
        CollectionExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(user.getId());
        List<Collection> list = collectionService.selectByExample(example);
        List<Blog> blogs = new ArrayList<>();
        for (Collection c : list) {
            blogs.add(blogService.selectByPrimaryKey(c.getBld()));
        }
        blogs.sort(Comparator.comparing(Blog::getBid).reversed());
        map.put("collections", list);
        map.put("blogs", blogs);
        return map;
    }

    //取消收藏
    @RequestMapping("/delcol/{bld}")
    @ResponseBody
    public String delcol(HttpSession session,
                         @PathVariable("bld") String bld) {
        User u = (User) session.getAttribute("user");
        CollectionExample example = new CollectionExample();
        CollectionExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andBldEqualTo(Integer.parseInt(bld));
        try {
            collectionService.deleteByExample(example);
            return "取消收藏成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "取消收藏失败!";
        }
    }

    //批量操作
    @RequestMapping("/cleancol")
    @ResponseBody
    public String cleancol(HttpSession session,
                           @RequestParam("li") String li) {
        User u = (User) session.getAttribute("user");
        String[] tip = li.split(",");
        if (tip.length != 0) {
            for (String a : tip) {
                CollectionExample example = new CollectionExample();
                CollectionExample.Criteria criteria = example.createCriteria();
                criteria.andIdEqualTo(u.getId());
                criteria.andBldEqualTo(Integer.parseInt(a));
                collectionService.deleteByExample(example);
            }
            return "批量操作成功!";
        } else {
            return "没有收藏可以清理!";
        }
    }

    //修改资料
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, Object> update(HttpSession session,
                                      @RequestParam("nc") String name,
                                      @RequestParam("uid") String uid,
                                      @RequestParam("qm") String auto,
                                      @RequestParam("sex") String sex,
                                      @RequestParam("birthday") String birthday,
                                      @RequestParam("prof") String prof,
                                      @RequestParam("school") String school,
                                      @RequestParam("desc") String desc) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        if (user != null) {
            String temp = user.getUid();
            try {
                user.setUid(uid);
                userService.updateByPrimaryKey(user);
            } catch (Exception e) {
                user.setUid(temp);
                map.put("msg", "该ID已存在，请重新设置!");
                return map;
            }
            user.setName(name);
            user.setAutograph(auto);
            if ("男".equals(sex)) {
                user.setSex("1");
            } else {
                user.setSex("0");
            }
            user.setBirthday(birthday);
            user.setProfessional(prof);
            user.setSchool(school);
            user.setDescription(desc);
            try {
                userService.updateByPrimaryKey(user);
                map.put("msg", "修改成功!");
            } catch (Exception e) {
                map.put("msg", "修改失败!");
            }
        } else {
            map.put("msg", "修改失败！");
        }
        session.setAttribute("user", user);
//        setfollw(model, uid);
//        map.put("user1", selectByUid(uid));
        return map;
    }

    //判断是否为整数
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    //关注
    @RequestMapping("/addfollow")
    @ResponseBody
    public Map<String, Object> addfollow(HttpSession session,
                                         @RequestParam("did") String did) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        User u2 = selectByUid(did);
        Follow follow = new Follow();
        follow.setId(u.getUid());
        follow.setImg(u.getImg());
        follow.setDid(u2.getUid());
        follow.setDimg(u2.getImg());
        follow.setDname(u2.getName());
        try {
            followService.insert(follow);
            u.setFollows(u.getFollows() + 1);
            userService.updateByPrimaryKey(u);
            u2.setFans(u2.getFans() + 1);
            userService.updateByPrimaryKey(u2);
            map.put("msg", "关注成功!");
        } catch (DuplicateKeyException e) {
            map.put("msg", "你已经关注过该用户了!");
            e.printStackTrace();
        }
        return map;
    }

    //取消关注
    @RequestMapping("/delfollow")
    @ResponseBody
    public Map<String, Object> delfollow(HttpSession session,
                                         @RequestParam("did") String did) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        User u2 = selectByUid(did);
        FollowExample example = new FollowExample();
        FollowExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getUid());
        criteria.andDidEqualTo(u2.getUid());
        try {
            followService.deleteByExample(example);
            u.setFollows(u.getFollows() - 1);
            userService.updateByPrimaryKey(u);
            u2.setFans(u2.getFans() - 1);
            userService.updateByPrimaryKey(u2);
            map.put("msg", "取消关注成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "取消关注失败!");
        }
        return map;
    }

    //判断是否关注
    @RequestMapping("/checkfol/{bid}")
    @ResponseBody
    public String checkfol(HttpSession session,
                           @PathVariable("bid") String bid) {
        User u = (User) session.getAttribute("user");
        if (u == null) {
            return "none";
        }
        if (u.getUid().equals(bid)) {
            return "none";
        }
        FollowExample example = new FollowExample();
        FollowExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getUid());
        criteria.andDidEqualTo(bid);
        if (followService.selectByExample(example).size() == 0) {
            return "no";
        } else {
            return "yes";
        }

    }

    //获取关注集合
    public List<Follow> selectfollows(String id) {
        FollowExample example = new FollowExample();
        FollowExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        try {
            return followService.selectByExample(example);
        } catch (Exception e) {
            return null;
        }
    }

    //获取粉丝集合
    public List<User> selectfans(String did) {
        FollowExample example = new FollowExample();
        FollowExample.Criteria criteria = example.createCriteria();
        criteria.andDidEqualTo(did);
        try {
            List<Follow> follow = followService.selectByExample(example);
            List<User> fans = new ArrayList<>();
            for (Follow f : follow) {
                fans.add(userSelectByUid(f.getId()));
            }
            return fans;
        } catch (Exception e) {
            return null;
        }
    }

    //获取blog集合
    public List<Blog> blogSelectbyid(int id) {
        BlogExample example = new BlogExample();
        BlogExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        try {
            return blogService.selectByExample(example);
        } catch (Exception e) {
            return null;
        }
    }

    //获取浏览历史集合
    public List<History> historySelectByid(int id) {
        HistoryExample example = new HistoryExample();
        HistoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        try {
            return historyService.selectByExample(example);
        } catch (Exception e) {
            return null;
        }
    }

    //删除浏览历史
    @RequestMapping("/delhisbyhid")
    @ResponseBody
    public Map<String, Object> delhisbyhid(@RequestParam("hid") String hid) {
        Map<String, Object> map = new HashMap<>();
        try {
            historyService.deleteByPrimaryKey(Integer.parseInt(hid));
            map.put("msg", "删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "删除失败!");
        }
        return map;
    }

    //清空浏览历史
    @RequestMapping("/emptyhisbyid")
    @ResponseBody
    public Map<String, Object> emptyhisbyid(@RequestParam("id") String id) {
        Map<String, Object> map = new HashMap<>();
        HistoryExample example = new HistoryExample();
        HistoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(Integer.parseInt(id));
        try {
            historyService.deleteByExample(example);
            map.put("msg", "清空浏览历史成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "清空浏览历史失败!");
        }
        return map;
    }

    //安全管理
    @RequestMapping("/usersafe")
    public String usersafe(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("iplogs", getIpByid(user.getId()));
        return "FrontPages/login/usersafe";
    }

    //修改密码
    @RequestMapping("/changebyold")
    @ResponseBody
    public Map<String, Object> changepass1(HttpSession session,
                                           @RequestParam("old-password") String old_p,
                                           @RequestParam("new-password") String new_p,
                                           @RequestParam("re-password") String re_p
    ) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        if (old_p.equals("")) {
            map.put("msg", "请输入密码!");
            return map;
        }
        if (new_p.equals("")) {
            map.put("msg", "新密码不能为空!");
            return map;
        }
        if (re_p.equals("")) {
            map.put("msg", "请确认密码!");
            return map;
        }
        if (u.getPassword().equals(md5(old_p))) {
            if (!new_p.equals(old_p)) {
                if (new_p.equals(re_p)) {
                    u.setPassword(md5(new_p));
                    userService.updateByPrimaryKey(u);
                    map.put("msg", "修改密码成功!");
                } else {
                    map.put("msg", "两次输入的密码不相同!");
                }
            } else {
                map.put("msg", "新密码不能和旧密码相同!");
            }
        } else {
            map.put("msg", "密码输入错误!");
        }
        return map;
    }

    //修改密码邮箱
    @RequestMapping("/changebyema")
    @ResponseBody
    public Map<String, Object> changepass2(HttpSession session,
                                           @RequestParam("email") String email,
                                           @RequestParam("verification") String verification,
                                           @RequestParam("new-password") String password
    ) {
        Map<String, Object> map = new HashMap<>();
        if (selectByEmail(email) != null) {
            User user = selectByEmail(email);
            if (session.getAttribute("verfication") != null) {
                if (session.getAttribute("verfication").equals(verification)) {
                    if (user.getPassword().equals(md5(password))) {
                        map.put("msg", "旧密码不能与新密码相同!");
                    } else {
                        user.setPassword(md5(password));
                        userService.updateByPrimaryKey(user);
                        map.put("msg", "修改密码成功!");
                    }
                } else
                    map.put("msg", "验证码输入错误!");
            } else
                map.put("msg", "还没有发送验证码!");
        } else
            map.put("msg", "邮箱输入错误!");
        session.removeAttribute("verfication");
        return map;
    }

    //修改手机
    @RequestMapping("/changephone")
    @ResponseBody
    public Map<String, Object> changephone(HttpSession session,
                                           @RequestParam("verification") String verification,
                                           @RequestParam("new-phone") String nphone
    ) {
        Map<String, Object> map = new HashMap<>();
        if (nphone != "" && isInteger(nphone)) {
            User user = (User) session.getAttribute("user");
            if (session.getAttribute("verfication") != null) {
                if (session.getAttribute("verfication").equals(verification)) {
                    if (user.getPhone().equals(nphone)) {
                        map.put("msg", "新的手机号码不能和旧手机相同!");
                    } else {
                        user.setPhone(Integer.valueOf(nphone));
                        userService.updateByPrimaryKey(user);
                        map.put("msg", "修改手机成功!");
                    }
                } else
                    map.put("msg", "验证码输入错误!");
            } else
                map.put("msg", "还没有发送验证码!");
        } else
            map.put("msg", "手机号不能为空!");
        session.removeAttribute("verfication");
        return map;
    }

    //修改邮箱
    @RequestMapping("/changeemail")
    @ResponseBody
    public Map<String, Object> changeemail(HttpSession session,
                                           @RequestParam("verification") String verification,
                                           @RequestParam("new-email") String nemail
    ) {
        Map<String, Object> map = new HashMap<>();
        if (nemail != "") {
            User user = (User) session.getAttribute("user");
            if (session.getAttribute("verfication") != null) {
                if (session.getAttribute("verfication").equals(verification)) {
                    if (user.getEmail().equals(nemail)) {
                        map.put("msg", "新的邮箱不能和旧邮箱相同!");
                    } else {
                        String temp = user.getEmail();
                        try {
                            user.setEmail(nemail);
                            userService.updateByPrimaryKey(user);
                            map.put("msg", "修改邮箱成功!");
                        } catch (Exception e) {
                            user.setEmail(temp);
                            map.put("msg", "该邮箱已存在，请重新输入!");
                            return map;
                        }
                    }
                } else
                    map.put("msg", "验证码输入错误!");
            } else
                map.put("msg", "还没有发送验证码!");
        } else
            map.put("msg", "邮箱不能为空!");
        session.removeAttribute("verfication");
        return map;
    }

    //获取iplog列表
    public List<Iplog> getIpByid(int id) {
        IplogExample example = new IplogExample();
        IplogExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        try {
            return iplogService.selectByExample(example);
        } catch (Exception e) {
            return null;
        }
    }

    //我的博客
    @RequestMapping("/userexh/{uid}")
    public String userexh(Model model,
                          @PathVariable("uid") String uid) {
        User user1 = selectByUid(uid);
        List<Blog> blogList = blogSelectbyid(user1.getId());
        model.addAttribute("user1", user1);
        model.addAttribute("blogs", blogList);
        model.addAttribute("count", blogList.size());
        return "FrontPages/login/userexhibition";
    }

    //消息中心
    @RequestMapping("/message")
    public String message(HttpSession session, Model model) {
        User u = (User) session.getAttribute("user");

        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andZidIsNotNull();
        List<Message> messages = messageService.selectByExample(example);
        messages.sort(Comparator.comparing(Message::getMid).reversed());
        List<Blog> blogs = new ArrayList<>();
        for (Message m : messages) {
            blogs.add(blogService.selectByPrimaryKey(m.getZid()));
        }
        model.addAttribute("messages", messages);
        model.addAttribute("blogs", blogs);
        return "FrontPages/login/message";
    }

    //获取点赞消息
    @RequestMapping("/zanmsg")
    @ResponseBody
    public Map<String, Object> zanmsg(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andZidIsNotNull();
        List<Message> messages = messageService.selectByExample(example);
        messages.sort(Comparator.comparing(Message::getMid).reversed());
        List<Blog> blogs = new ArrayList<>();
        for (Message m : messages) {
            blogs.add(blogService.selectByPrimaryKey(m.getZid()));
        }
        map.put("messages", messages);
        map.put("blogs", blogs);
        return map;
    }

    //获取收藏消息
    @RequestMapping("/colmsg")
    @ResponseBody
    public Map<String, Object> colmsg(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andBidIsNotNull();
        criteria.andZidIsNull();
        criteria.andCidIsNull();
        List<Message> messages = messageService.selectByExample(example);
        messages.sort(Comparator.comparing(Message::getMid).reversed());
        List<Blog> blogs = new ArrayList<>();
        for (Message m : messages) {
            blogs.add(blogService.selectByPrimaryKey(m.getBid()));
        }
        map.put("messages", messages);
        map.put("blogs", blogs);
        return map;
    }

    //获取评论消息
    @RequestMapping("/commsg")
    @ResponseBody
    public Map<String, Object> commsg(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andBidIsNotNull();
        criteria.andCidIsNotNull();
        List<Message> messages = messageService.selectByExample(example);
        messages.sort(Comparator.comparing(Message::getMid).reversed());
        List<Blog> blogs = new ArrayList<>();
        for (Message m : messages) {
            blogs.add(blogService.selectByPrimaryKey(m.getBid()));
        }
        map.put("messages", messages);
        map.put("blogs", blogs);
        return map;
    }

    //获取回复消息
    @RequestMapping("/repmsg")
    @ResponseBody
    public Map<String, Object> repmsg(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(u.getId());
        criteria.andRidIsNotNull();
        List<Message> messages = messageService.selectByExample(example);
        messages.sort(Comparator.comparing(Message::getMid).reversed());
        List<Comment> comments = new ArrayList<>();
        List<Reply> replies = new ArrayList<>();
        for (Message m : messages) {
            comments.add(commentService.selectByPrimaryKey(m.getCid()));
            replies.add(replyService.selectByPrimaryKey(m.getRid()));
        }
        map.put("messages", messages);
        map.put("comments", comments);
        map.put("replies", replies);
        return map;
    }

    //删除消息
    @RequestMapping("/delmsg/{mid}")
    @ResponseBody
    public String delmsg(@PathVariable("mid") String mid) {
        try {
            messageService.deleteByPrimaryKey(Integer.parseInt(mid));
            return "删除成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败!";
        }
    }

    //清除消息
    @RequestMapping("/cleanmsg")
    @ResponseBody
    public String cleanmsg(@RequestParam("li") String li) {
        String[] tip = li.split(",");
        if (tip.length != 0) {
            for (String a : tip) {
                messageService.deleteByPrimaryKey(Integer.parseInt(a));
            }
            return "清除成功!";
        } else {
            return "没有消息可以清理!";
        }
    }

    //bottom的广告
    @RequestMapping("/botadv")
    public String botadv() {
        return "FrontPages/common/bottom-adver";
    }
}
